package com.cangxuan.app;

import android.app.AlertDialog;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import cn.jpush.android.api.JPushInterface;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.entity.User;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.DownloadUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.UserUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;


/**
 * 主活动，应用入口
 * 作者：洪老师
 */
public class MainActivity extends BaseActivity {
    public NavController navController;
    Handler handler = new Handler();
    ImageView loadImg;
    String version;
    AlertDialog.Builder alertDialogBuilder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //初始化并检查数据库
        String dbName = "app.db";   //数据库文件名
        String dbDirectory = "/data/data/" + getPackageName() + "/databases";   //数据库存放位置
        File dbDirectoryFile = new File(dbDirectory);   //数据库存放位置对象
        if (!dbDirectoryFile.exists()) dbDirectoryFile.mkdirs();
        File dbFile = new File(dbDirectory, dbName);    //保存的目录文件
        if (!dbFile.exists()) {
            //如果目标文件不存在
            try {
                dbFile.createNewFile();     //创建新文件
                //将raw下面的app.db通过字节输入流的方式读取出来，再写入到dbFile文件中
                InputStream inputStream = getResources().openRawResource(R.raw.app);    //源文件输入流
                byte[] bytes = new byte[inputStream.available()];   //数据库文件的字节数组
                inputStream.read(bytes);    //从源文件读取字节出来存放到bytes数组
                inputStream.close();
                FileOutputStream fileOutputStream = new FileOutputStream(dbFile);       //目录文件的输出流
                fileOutputStream.write(bytes);  //将bytes字节写入到目的文件中
                fileOutputStream.close();
                Log.i("MainActivity", "Sqlite 数据库导入完毕！");
            } catch (IOException e) {
                Log.e("MainActivity", "Sqlite 数据库导入失败");
                throw new RuntimeException(e);
            }
        } else {
            Log.i("MainActivity", "Sqlite 数据库已存在，无须导入。");
        }
        //获取SQLiteOpenHelper实例
        SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper(context, dbName, null, 1) {
            @Override
            public void onCreate(SQLiteDatabase sqLiteDatabase) {
                //当首次安装APP后，在该方法里去写建表的SQL语句
            }

            @Override
            public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
            }
        };
        DB.sqLiteDatabase = sqLiteOpenHelper.getWritableDatabase();


        setContentView(R.layout.activity_main);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this, R.color.preLoading));
        loadImg = findViewById(R.id.loadImg);
        version=getResources().getString(R.string.app_version);
        alertDialogBuilder = new AlertDialog.Builder(this);
        new Thread(()->{
            try {
                Thread.sleep(3000);
                handler.post(()->{
                   loadImg.setVisibility(View.GONE);
                    window.setStatusBarColor(ContextCompat.getColor(this, R.color.background));
                });
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        //发起子线程去检查更新
        new Thread(() -> {
            setUpdateOnClick("/api/version/ver");
        }).start();
        // 隐藏ActionBar
        getSupportActionBar().hide();
        // 获取界面上的底部导航栏控件
        BottomNavigationView bottomNavigationView = findViewById(R.id.navBottom);
        // 创建一个导航控制器
        navController = Navigation.findNavController(this, R.id.fragmentNav);
        // //设置底部导航栏控件与导航控制器的关联
        NavigationUI.setupWithNavController(bottomNavigationView, navController);

        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Thread thread = new Thread(() -> {
            //构建header
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", DeviceUtils.getDeviceID());
            String jsonString = HttpUtils.post("/api/checkLogin", headers, null);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                handler.post(()->{
                    Toast.makeText(context, "服务器异常", Toast.LENGTH_SHORT).show();
                });
                return;
            }
            if (jsonResponse.getInteger("status") != HttpURLConnection.HTTP_OK) {
                User user = UserUtils.getUser(context);
                if (user != null) {
                    user.setId(0);
                    UserUtils.setUser(context, user);
                }
            }
        });
        thread.start();
    }
    public void setUpdateOnClick(String url){
        Thread thread=new Thread(() -> {
            String s = HttpUtils.get(url);
            JSONObject jsonRs=JSONObject.parseObject(s);
            if(jsonRs.getInteger("status")== HttpURLConnection.HTTP_OK){
                Map value = jsonRs.getObject("value",Map.class);
                String illustrate=value.get("illustrate").toString();
                String versionNumber=value.get("versionNumber").toString();
                Boolean isItMandatory=new Boolean(value.get("isItMandatory").toString());
                String ur=HttpUtils.host+ File.separator+"cangxuan."+versionNumber+".apk";

                handler.post(()->{
                    if((!versionNumber.equals(version))&&isItMandatory==true){
                        alertDialogBuilder.setTitle(versionNumber+"版本更新");
                        alertDialogBuilder.setMessage(illustrate);
                        alertDialogBuilder.setPositiveButton("确认更新", (dialogInterface, i) -> {
                            //必须更新的点击事件
                            new DownloadUtils(MainActivity.this, MainActivity.this, ur, "cangxuan");
                            Toast.makeText(MainActivity.this, "正在下载，请在通知栏中查看下载状态", Toast.LENGTH_LONG).show();
                        });
                        alertDialogBuilder.setCancelable(false);
                        alertDialogBuilder.show();
                    }else if((!versionNumber.equals(getResources().getString(R.string.app_version)))&&isItMandatory==false){
                        alertDialogBuilder.setTitle(versionNumber+"版本更新");
                        alertDialogBuilder.setMessage(illustrate);
                        alertDialogBuilder.setPositiveButton("确认更新", (dialogInterface, i) -> {
                            //选择更新的点击事件
                            new DownloadUtils(MainActivity.this, this, ur, "藏选");
                            Toast.makeText(MainActivity.this, "正在下载，请在通知栏中查看下载状态", Toast.LENGTH_LONG).show();
                        });
                        alertDialogBuilder.setNegativeButton("取消更新",(dialogInterface, i)->{
                            //选择取消更新的点击事件
                        });
                        alertDialogBuilder.setCancelable(true);
                        alertDialogBuilder.show();
                    }
                });
            }else {
                handler.post(()->{
                    Toast.makeText(getApplicationContext(), jsonRs.getString("message"), Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        });
        thread.start();
    }


}